package com.borya.task.impl;

import java.time.Clock;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.log4j.Logger;

import com.borya.dao.MerchantDAO;
import com.borya.framework.annotation.Autowired;
import com.borya.framework.annotation.Component;
import com.borya.model.db.Message;
import com.borya.model.db.ShqpInfo;
import com.borya.task.AbstractTaskService;
import com.borya.util.Constant;
import com.borya.util.DateUtils;
import com.borya.util.StringUtil;

@Component("shqpTask")
public class ShqpTask extends AbstractTaskService {
	
	private Logger log = Logger.getLogger(getClass());
	
	@Autowired("merchantDAO")
	private MerchantDAO merchantDAO;

	public ShqpTask() {
		super(Constant.SHQP_MSG_START);
	}

	@Override
	public void process(){
		try {
			log.info("检查是否发送授权牌过期消息");
			//当前日期2个月后
			String endTime = DateUtils.getExpectDate(0,2,0,"yyyyMMdd");
			final int endDate = Integer.parseInt(endTime);
			List<ShqpInfo> list = merchantDAO.timeEndList(endDate);
			if(list == null){
				log.error("timeEndList return null,"+endDate);
				return;
			}
			if(list.size()==0){
				log.info("无过期授权牌，过期时间："+endDate);
				return;
			}
			List<Message> msgList = list.stream().map(x->msgContent(x)).collect(Collectors.toList());
			boolean res = merchantDAO.shqpMsg(list,msgList);
			log.info("授权牌过期消息发送结果："+res);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}



	private Message msgContent(ShqpInfo shqpInfo){
		String endDate = shqpInfo.getShqpEndTime()+"";
		String year = endDate.substring(0,4);
		String month = endDate.substring(4,6);
		String day = endDate.substring(6,8);
		String content;
		if(shqpInfo.getSourceType() == 1){
			content = String.format("尊敬的商户，您的%s远特商户授权牌将于%s年%s月%s日到期，" +
					"可通过“授权牌管理”页面申请商户授权牌续约操作。感谢您长期以来对%s的支持与配合！",
					"卡盟",year,month,day,"卡盟");
		} else {
			content = String.format("尊敬的商户，您的远特商户授权牌将于%s年%s月%s日到期。" +
							"感谢您长期以来的支持与配合！",
					year,month,day);
		}
		return makeMsg(shqpInfo.getUserId(),content,"246");
	}

	/**
	 * 激活结果给商户发送消息
	 * @param userId
	 */
	private Message makeMsg(String userId, String contentStr, String msgType){
		Message msg = new Message();
		final long curTime = Clock.systemDefaultZone().millis();
		msg.setMsgId(StringUtil.getMsgId(curTime));
		msg.setMsgType(Message.MessageType.BUSINESS);
		msg.setSender("system");
		msg.setReceiver(userId);
		msg.setCreatTime(curTime);
		msg.setExpTime(curTime + 30 * 24 * 60 *60 *1000);
		StringBuilder content = new StringBuilder(256);
		content.append("{");
		content.append("\"type\":").append(msgType);
		content.append(",\"title\": \"商户授权牌过期提醒\"");
		content.append(",\"annex\":[]");
		content.append(",\"content\":\"");
		content.append(contentStr);
		content.append("\"");
		content.append(",\"redirectUrl\":\"\"");
		content.append("}");
		msg.setContent(content.toString());

		return msg;

	}
}
